package com.imdroid.lite.net.udp;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.nio.ByteBuffer;

import android.location.Location;

import com.imdroid.lite.IMDroid;
import com.imdroid.lite.model.Team;

public class UDPSendUtilRealtime {
	
	private static final byte[] voice_controls = new byte[18];
	
	public static void sendAudioPack(ByteBuffer audioData){
		byte[] data = new byte[548];
		ByteBuffer buffer = ByteBuffer.wrap(data);
		initControlsRuntime();
		buffer.put(voice_controls, 0, 18);
		buffer.put(audioData);
		buffer.flip();
		DatagramPacket packet = new DatagramPacket(data, audioData.limit() + 18);
		packet.setAddress(ServerAddress.address);
		packet.setPort(ServerAddress.port);
		UDPServer.sendPacket(packet);
	}
	
	public static void sendTeamLocation(Location loc){
		StringBuilder locStr = new StringBuilder();
		locStr.append(Team.getCurrentTeam().getTeamId()).append("&&");
		locStr.append(loc.getLatitude()).append("&&");
		locStr.append(loc.getLongitude()).append("&&");
		locStr.append(loc.getSpeed()).append("&&");
		locStr.append(IMDroid.getUser().getUser_name()).append("&&");
		locStr.append(loc.getBearing()).append("&&1");// 1 is device type
		byte[] payload = null;
		try {
			payload = locStr.toString().getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] dataToSend = new byte[18 + payload.length];
		dataToSend[0] |= 1 << 2; // broadcast
		dataToSend[1] = FileTypes.TEAM_LOCATION;
		System.arraycopy(IntegerTransfer.longToByte(System.currentTimeMillis()), 0, dataToSend, 2, 8); // msgId
		System.arraycopy(IntegerTransfer.intToByte(IMDroid.getUser().getUser_id()), 0, dataToSend, 10, 4); // user Id
		System.arraycopy(IntegerTransfer.intToByte((int)Team.getCurrentTeam().getTeamId()), 0, dataToSend, 14, 4);
		System.arraycopy(payload, 0, dataToSend, 18, payload.length);
		DatagramPacket packet = new DatagramPacket(dataToSend, dataToSend.length);
		packet.setAddress(ServerAddress.address);
		packet.setPort(ServerAddress.port);
		UDPServer.sendPacket(packet);
	}
	
	private static void initControlsRuntime(){
		System.arraycopy(IntegerTransfer.intToByte((int)Team.getCurrentTeam().getTeamId()), 0, voice_controls, 14, 4); // 队伍ID
	}
	
	static {
		voice_controls[0] |= 1 << 1; // 大文件
		voice_controls[0] |= 1 << 2; // 广播
		// 忽略信息ID
		System.arraycopy(IntegerTransfer.intToByte(IMDroid.getUser().getUser_id()), 0, voice_controls, 10, 4); // 发送者用户ID
		voice_controls[1] = FileTypes.REAL_TIME; // 文件类型：实时语音数据
	}

}
